//index.js
var util = require('../../utils/util.js');
//获取应用实例
var app = getApp()
var searchUrl = 'https://apis.map.qq.com/ws/place/v1/search'
var qqUrl = 'https://apis.map.qq.com/ws/coord/v1/translate'
var qqKey = 'XKGBZ-ZWY2J-ARQFP-FPGU6-HCCC2-T3BZM'
var qqBasketMarkers = []
var curAddr = ''
var curAddrPos = null
Page({
  data: {
    latitude: 0,
    longitude: 0,
    mapStyle: 'width: 100%; height: 95vh;',
    markers: "",
    circles: "",
    polyline: "",
    controls: [{
      id: 1,
      iconPath: '/resources/help.png',
      position: {
        left: 20,
        top: 20,
        width: 30,
        height: 30
      },
      clickable: true
    }
      // , {
      //   id: 2,
      //   iconPath: '/resources/plus.png',
      //   position: {
      //     left: 20,
      //     top: 60,
      //     width: 30,
      //     height: 30
      //   },
      //   clickable: true
      // }
    ],
    includePoints: '',
    addr: ''
  },
  //事件处理函数
  controltap: function (e) {
    if (e.controlId == 1) {
      wx.navigateTo({
        url: '../info/info'
      })
    } else if (e.controlId == 2) {
      wx.chooseLocation({
        success: function (res) {
          console.log(res.longitude + "," + res.latitude)
          addMarker(res.longitude, res.latitude)
        },
        fail: function (e) {
          console.log('chooseLocation fail', e)
        }
      })
    }
  },
  markertap: function () {
  },
  onCallouttap: function (e) {
    // app.indexPage.setData({ addr: 'onCallouttap' })
    var currentMarker = null
    for (var i = 0; i < qqBasketMarkers.length; i++) {
      if (qqBasketMarkers[i] != null) {
        var id = qqBasketMarkers[i].id
        if (id == e.markerId) {
          currentMarker = qqBasketMarkers[i]
          break
        }
      }
    }
    if (currentMarker != null) {
      // app.indexPage.setData({ addr: currentMarker.name })
      var x = currentMarker.longitude
      var y = currentMarker.latitude
      wx.showModal({
        title: '地图导航',
        content: '是否要去这里？',
        success: function (res) {
          if (res.confirm) {
            // 导航
            wx.openLocation({
              latitude: y,
              longitude: x,
              scale: 28
            })
          }
        }
      })
    }
  },
  maptap: function () {
  },
  onLoad: function () {
    app.indexPage = this
    var that = this

    app.getUserInfo(function (userInfo) {
      var that = this
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              var nickName = res.userInfo.nickName;

              // 设置全局变量
              var app = getApp()

              // 上传坐标
              if (nickName != '') {
                util.uploadGPS(nickName)
              } else {
                console.log('nickName is null')
              }
            }
          })
        }
      })
    })

    wx.getLocation({
      type: 'gcj02',
      success: function (locationData) {
        var latitude = locationData.latitude
        var longitude = locationData.longitude
        console.log(longitude + "," + latitude)

        that.setData({ longitude: longitude, latitude: latitude })

        searchBasket(longitude, latitude)

        util.getAddr(longitude, latitude, handleGetAddr)
      }
    })
  },
  onAddrInput: function (e) {
    // var text = e.detail.value
    // console.log("text = " + text)
  },
  onAddrConfirm: function (e) {
    var addr = e.detail.value
    util.geocode(addr, handleGeocode)
    // console.log("text = " + text)
  },
  onAddrFocus: function (e) {
    var text = e.detail.value
    // if (text == '') {
    // console.log("text is empty")
    app.indexPage.setData({ addr: curAddr })
    // }
  }
})

function addMarker(longitude, latitude) {
  wx.request({
    url: qqUrl,
    data: {
      locations: latitude + ',' + longitude,
      type: 1,
      key: qqKey
    },
    success: function (res) {
      // console.log("res.data:" + res.data)
      var status = res.data.status
      if (status == 0) {
        var locations = res.data.locations
        var location = locations[0]

        var marker = new Object()
        marker.id = qqBasketMarkers.length;
        marker.longitude = location.lng
        marker.latitude = location.lat
        marker.name = 'abc'
        marker.iconPath = '/resources/ball.png'
        marker.width = 40
        marker.height = 27
        qqBasketMarkers.push(marker)
        app.indexPage.setData({ markers: qqBasketMarkers })
      }
    },
    fail: function (res) {
    }
  })
}

function searchBasket(x, y) {
  var distance = 5000
  var boundary = 'nearby(' + y + ',' + x + ',' + distance + ')'

  wx.request({
    url: searchUrl,
    data: {
      boundary: boundary,
      keyword: '篮球场',
      page_size: 20,
      page_index: 1,
      orderby: '_distance',
      key: qqKey
    },
    success: function (res) {
      // console.log("(searchBasket)res.data:" + res.data)
      if (res.data.status == 0) {
        var count = res.data.count
        var data = res.data.data
        var markers = []
        // 居中显示 ？
        var anchor = new Object()
        anchor.x = 0.5
        anchor.y = 0.5
        for (var i = 0; i < count; i++) {
          var basketballPlace = data[i]
          if (basketballPlace != null) {
            var title = basketballPlace.title
            var basketballLocation = basketballPlace.location
            var lng = basketballLocation.lng
            var lat = basketballLocation.lat
            // console.log("basketballLocation:" + lng + "," + lat)
            var callout = new Object()
            callout.content = title
            callout.display = 'BYCLICK'
            callout.bgColor = '#C6E2FF'
            var marker = new Object()
            marker.id = i + 1;
            marker.longitude = lng
            marker.latitude = lat
            marker.name = title
            marker.anchor = anchor
            marker.callout = callout
            marker.iconPath = '/resources/ball.png'
            marker.width = 40
            marker.height = 27
            markers.push(marker)
          }
        }
        if (curAddrPos != null) {
          var marker = new Object()
          marker.id = markers.length;
          marker.longitude = curAddrPos.x
          marker.latitude = curAddrPos.y
          marker.name = curAddr
          marker.iconPath = '/resources/pos.png'
          marker.width = 20
          marker.height = 23
          markers.push(marker)
        }
        app.indexPage.setData({ markers: markers, includePoints: markers })

        qqBasketMarkers = markers
      } else {
        console.log('searchBasket fail')
      }
    },
    fail: function (e) {
      console.log('searchBasket fail', e)
    }
  })
}

function handleGetAddr(addr) {
  curAddr = addr
}

function handleGeocode(x, y) {
  curAddrPos = new Object()
  curAddrPos.x = x
  curAddrPos.y = y
  console.log('in handleGeocode. x = ' + x + ',y = ' + y)
  searchBasket(x, y)
}